package com.twotiger.and.activity.account.recharge;

import java.util.Timer;
import java.util.TimerTask;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.AlertDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import app.twotiger.p2p.R;

import com.twotiger.and.activity.account.cash.CashPage;
import com.twotiger.and.activity.base.BaseActivity;
import com.twotiger.and.util.LogUtil;
import com.twotiger.and.util.PackageUtils;
import com.twotiger.and.util.PromptManager;
import com.twotiger.and.util.StringUtils;
import com.twotiger.and.util.ViewUtils;

/**
 * 
 * @Description:
 * 汇付天下页面充值 
 * @Author douxy
 * @Date 2015年8月12日 下午1:51:45
 */
public class RechargeWebViewPage extends BaseActivity {

    public static final String SEARCH_HISTORY = "WebViewPage";
    private WebView mWebView;
    private String type;

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
        case R.id.sub_title_left_ll:
            if (ViewUtils.isFastDoubleClick(view)) {
                return;
            }
            htmlGoBack();
            break;
        default:
            break;
        }
    }

    @Override
    protected void setListener() {

    }

    @SuppressWarnings({ "deprecation" })
    @SuppressLint("SetJavaScriptEnabled")
    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
    @Override
    protected void processLogic() {
        try {
            if (mWebView != null) {
                mWebView.setWebViewClient(new NewsClient());
                String url = getIntent().getStringExtra("url");
                String titleText = getIntent().getStringExtra("title");
                type = getIntent().getStringExtra("type");
                if (StringUtils.isEmpty(url)) {
                    url = "http://www.twotiger.com";
                }
                mWebView.loadUrl(url);
                LogUtil.info("url" + url);
                LogUtil.info("title" + titleText);
                WebSettings mWebSettings = mWebView.getSettings();
                mWebSettings.setJavaScriptEnabled(true);
                String appCachePath = RechargeWebViewPage.this.getCacheDir().getAbsolutePath();
                mWebSettings.setAppCacheEnabled(true);
                mWebSettings.setAppCachePath(appCachePath);
                mWebSettings.setAppCacheMaxSize(8 * 1024 * 1024);
                mWebSettings.setAllowFileAccess(true);
                mWebSettings.setCacheMode(WebSettings.LOAD_DEFAULT);
                mWebSettings.setDisplayZoomControls(true);
                mWebSettings.setBuiltInZoomControls(true);
                mWebSettings.setUseWideViewPort(true);
                mWebSettings.setSupportZoom(true);
                String ua = mWebSettings.getUserAgentString();
                ua = ua + " "
                     + String.format("TwoTiger/%s", PackageUtils.getAppVersionName(mContext));
                mWebSettings.setUserAgentString(ua);
                mWebView.setWebChromeClient(new MyWebChromeClient());
                mWebView.setOnTouchListener(new View.OnTouchListener() {
                    @SuppressLint("ClickableViewAccessibility")
                    @Override
                    public boolean onTouch(View v, MotionEvent event) {
                        switch (event.getAction()) {
                        case MotionEvent.ACTION_DOWN:
                        case MotionEvent.ACTION_UP:
                            if (!v.hasFocus()) {
                                v.requestFocus();
                            }
                            break;
                        }
                        return false;
                    }
                });
            } else {

            }
            Timer timer = new Timer();
            // 点击1毫秒开始执行，没个一秒执行一次
            timer.scheduleAtFixedRate(new TimerTask() {
                @Override
                public void run() {
                    PromptManager.closeWebviewLoadDataDialog();
                }
            }, 3000, 1000);
        } catch (Exception e) {
            LogUtil.info(String.valueOf(e.getMessage()));
        }
    }

    /**
     * 开通三方：openPayment
     * <p>
     * 投资接口：invest
     * <p>
     * 充值接口：recharge
     * <p>
     * 绑定银行卡：bindBankCard
     * <p>
     * 提现接口：cash
     */
    class NewsClient extends WebViewClient {

        private AlertDialog alertDialog;

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
            //			if (!isHidden())
            //				PromptManager.showLoadDataDialog(getActivity(), "正在加载...");
            //			mWebView.postDelayed(new Runnable() {
            //				@Override
            //				public void run() {
            //					PromptManager.closeWebviewLoadDataDialog();
            //				}
            //			}, 3000);
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            PromptManager.closeWebviewLoadDataDialog();
        }

        // @Override
        // public void onLoadResource(WebView view, String url) {
        // super.onLoadResource(view, url);
        // PromptManager.closeLoadDataDialog();
        // }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, final String url) {
            try {
                //				view.loadUrl(url);
                String head = String.format("TwoTiger/appinfo:%s android;",
                    PackageUtils.getAppVersionName(mContext));
                view.postUrl(url, head.getBytes());
                // 成功回调：
                // 回调url 为 /app/notice?msg=***成功***&url=****
                // 失败回调：不会出现成功字眼！！
                // 回调url 为 /app/notice?msg=***&url=****
                if (url != null && url.contains("success")) {
                    mWebView.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            final Bundle bundle = new Bundle();
                            if (!StringUtils.isEmpty(type)) {
                                if (type.equals("openPayment")) {
                                    alertDialog = PromptManager.showSimpleCustomDialog(
                                        RechargeWebViewPage.this, "提示", "开通三方支付成功", "确认",
                                        new View.OnClickListener() {
                                            @Override
                                            public void onClick(View v) {
                                                popBackStack();
                                                if (alertDialog != null) {
                                                    alertDialog.dismiss();
                                                }
                                            }
                                        });
                                    if (alertDialog != null) {
                                        alertDialog.show();
                                    }
                                } else if (type.equals("invest")) {
                                    alertDialog = PromptManager.showSimpleCustomDialog(
                                        RechargeWebViewPage.this, "提示", "投资成功", "确认",
                                        new View.OnClickListener() {
                                            @Override
                                            public void onClick(View v) {
                                                if (alertDialog != null) {
                                                    alertDialog.dismiss();
                                                }
                                                RechargeWebViewPage.this.finish();
                                            }
                                        });
                                    if (alertDialog != null) {
                                        alertDialog.show();
                                    }

                                } else if (type.equals("recharge")) {
                                    alertDialog = PromptManager.showSimpleCustomDialog(
                                        RechargeWebViewPage.this, "提示", "充值成功", "确认",
                                        new View.OnClickListener() {
                                            @Override
                                            public void onClick(View v) {
                                                if (alertDialog != null) {
                                                    alertDialog.dismiss();
                                                }
                                            }
                                        });
                                    if (alertDialog != null) {
                                        alertDialog.show();
                                    }

                                } else if (type.equals("bindBankCard")) {
                                    alertDialog = PromptManager.showSimpleCustomDialog(
                                        RechargeWebViewPage.this, "提示", "绑定银行卡成功", "确认",
                                        new View.OnClickListener() {
                                            @Override
                                            public void onClick(View v) {
                                                if (alertDialog != null) {
                                                    alertDialog.dismiss();
                                                }
                                                popBackStack();
                                                bundle.clear();
                                                bundle.putString("title", "提现");
                                                Intent intent = new Intent(RechargeWebViewPage.this,
                                                    CashPage.class).putExtras(bundle);
                                                startNewActivity(intent, R.anim.push_left_in,
                                                    R.anim.push_left_out, false);
                                            }
                                        });
                                    if (alertDialog != null) {
                                        alertDialog.show();
                                    }

                                } else if (type.equals("cash")) {
                                    alertDialog = PromptManager.showSimpleCustomDialog(
                                        RechargeWebViewPage.this, "提示", "提现成功", "确认",
                                        new View.OnClickListener() {
                                            @Override
                                            public void onClick(View v) {
                                                if (alertDialog != null) {
                                                    alertDialog.dismiss();
                                                }
                                                popBackStack();
                                                showToast("提现成功");
                                                bundle.clear();
                                                bundle.putString("title", "提现");
                                                Intent intent = new Intent(RechargeWebViewPage.this,
                                                    CashPage.class).putExtras(bundle);
                                                startNewActivity(intent, R.anim.push_left_in,
                                                    R.anim.push_left_out, false);
                                            }
                                        });
                                    if (alertDialog != null) {
                                        alertDialog.show();
                                    }

                                }
                            }
                        }
                    }, 300);
                }
            } catch (Exception e) {
                LogUtil.info(String.valueOf(e.getMessage()));
            }

            return true;
        }
    }

    private void htmlGoBack() {
        try {
            String currentGoBackUrl = mWebView.getUrl();
            if (mWebView != null) {
                if (currentGoBackUrl != null) {
                    popBackStack();
                } else {
                    if (mWebView.canGoBack()) {
                        mWebView.goBack();
                        return;
                    }
                    finish();
                    overridePendingTransition(R.anim.push_right_in, R.anim.push_right_out);
                }
            }
        } catch (Exception e) {
            LogUtil.info(String.valueOf(e.getMessage()));
        }
    }

    public class MyWebChromeClient extends android.webkit.WebChromeClient {
        @Override
        public void onReceivedTitle(WebView view, String title) {
            super.onReceivedTitle(view, title);
            //			mActivity.sub_title_center_tv.setText("" + title);
            //			mActivity.sub_title_center_tv.setVisibility(View.VISIBLE);
        }

        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            super.onProgressChanged(view, newProgress);
            try {
                // if (newProgress > 5) {
                // PromptManager.closeLoadDataDialog();
                // } else {
                // PromptManager.showLoadDataDialog(mActivity, "正在加载...");
                // }
            } catch (IllegalArgumentException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        PromptManager.closeLoadDataDialog();
        // try {
        // if (null != mWebView) {
        // mWebView.destroy();
        // mWebView = null;
        // }
        // } catch (Exception e) {
        // LogUtil.info(String.valueOf(e.getMessage() + ""));
        // }
    }

    @Override
    protected void findViewById(View view) {
        mWebView = (WebView) view.findViewById(R.id.webview);

    }

    @Override
    protected View loadViewLayout(LayoutInflater inflater) {
        View contactsLayout = inflater.inflate(R.layout.charge_web_view_page, null);
        return contactsLayout;

    }

    @Override
    protected void onBackPress() {
        // TODO Auto-generated method stub

    }
}
